package org.jeecg.modules.yw.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.yw.entity.*;
import org.jeecg.modules.yw.mapper.AppointmentMapper;
import org.jeecg.modules.yw.service.EnterPriseService;
import org.jeecg.modules.yw.service.IAttendanceService;
import org.jeecg.modules.yw.service.IAttendapproveService;
import org.jeecg.modules.yw.service.MessagesService;
import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecg.modules.yw.utils.DateUtils;
import org.jeecg.modules.yw.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 考勤审批
 * @Author: jeecg-boot
 * @Date: 2025-04-10
 * @Version: V1.0
 */
@Api(tags = "考勤审批")
@RestController
@RequestMapping("/yw/attendapprove")
@Slf4j
public class AttendapproveController extends JeecgController<Attendapprove, IAttendapproveService> {
    @Autowired
    private IAttendapproveService attendapproveService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private IAttendanceService attendanceService;
    @Autowired
    EnterPriseService enterPriseService;
    @Autowired
    private MessagesService messagesService;
    @Resource
    AppointmentMapper appointmentMapper;

    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param id
     * @return
     */
    //@AutoLog(value = "考勤审批-分页列表查询")
    @ApiOperation(value = "考勤审批-分页列表查询", notes = "考勤审批-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<Attendapprove>> queryPageList(@RequestParam(name="id", required = false) String id,
                                                      @RequestParam(name="name", required = false) String name,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Attendapprove attendapprove= new Attendapprove();
        QueryWrapper<Attendapprove> queryWrapper = new QueryWrapper<>();
        attendapprove.setApprove("0");
        if(StringUtils.isNotBlank(id)) {
            queryWrapper.eq("id", id);
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(area)){
                String[] areas=area.split(",");
                StringBuffer st=new StringBuffer();
                for (int i = 0; i < areas.length; i++) {
                    st.append("\""+areas[i]+"\",");
                }
                st=st.deleteCharAt(st.length()-1);
                String sql="(select id from enterprise where city_code in ("+st.toString()+") " +
                        "or (province_code in  ("+st.toString()+") and city_code is null) )";
                queryWrapper.apply("workid in"+sql+"");
            }else{
                IPage<Attendapprove> result =new Page<>();
                return Result.OK(result);
            }
        }
        if(StringUtils.isNotBlank(name)) {
            String sql="(select id from enterprise where name like '%"+name+"%' and delflag='0')";
            queryWrapper.apply("workid in"+sql+"");
        }
        queryWrapper.orderByDesc("createtime");
        Page<Attendapprove> page = new Page<Attendapprove>(pageNo, pageSize);
        IPage<Attendapprove> pageList = attendapproveService.page(page, queryWrapper);
        if(pageList.getRecords()!=null) {
            pageList.getRecords().forEach(item -> {
                EnterPrise enterPrise = enterPriseService.getById(item.getWorkid());
                item.setWorkname(enterPrise.getName());
                item.setWorkphone(enterPrise.getMobile());
            });
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param attendapprove
     * @return
     */
    @AutoLog(value = "考勤审批-添加")
    @ApiOperation(value = "考勤审批-添加", notes = "考勤审批-添加")
    //@RequiresPermissions("org.jeecg.modules:attendapprove:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Attendapprove attendapprove) {
        attendapproveService.save(attendapprove);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "考勤审批-通过")
    @ApiOperation(value = "考勤审批-通过", notes = "考勤审批-通过")
    @RequestMapping(value = "/pass", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> pass(@RequestParam String id, HttpServletRequest request) {
        Attendapprove attendapprove = attendapproveService.getById(id);
        attendapprove.setApprove("1");
        attendapprove.setRemark("");
        attendapprove.setApprovetime(DateUtils.getCurrentDate());
        attendapprove.setApproveman(UserUtil.getUserId(request, sysBaseAPI));
        attendapproveService.updateById(attendapprove);
        Date today=DateUtils.getCurrentDate();
        boolean isInRange = !today.before(attendapprove.getStartTime()) && !today.after(attendapprove.getStopTime());
        if(isInRange) {        	
        	
        }
        String startTime = DateUtils.dateToStr(attendapprove.getStartTime());
    	String endTime = DateUtils.dateToStr(attendapprove.getStopTime());
    	if (startTime.equals(endTime)) {        	
            QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userid", attendapprove.getWorkid());
            queryWrapper.eq("attenddate", startTime);
            Attendance attendance = attendanceService.getOne(queryWrapper);
            if (attendance!=null)  {
            	attendance.setAttendtype(Integer.parseInt(attendapprove.getType()));
            	attendance.setAttenddate(DateUtils.strToDate(startTime));
            	attendanceService.updateById(attendance);
            } else {
            	attendance = new Attendance();
            	attendance.setId(CommonUtils.getID());
            	attendance.setUserid(attendapprove.getWorkid());
            	attendance.setAttenddate(attendapprove.getStartTime());
            	attendance.setCreatetime(DateUtils.getCurrentDate());
            	attendance.setAttendtype(0);
            	attendanceService.save(attendance);
            }
    	} else {
    		List<String> list = DateUtils.getAllDate(startTime, endTime);
    		for (String str: list) {
    			QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
	            queryWrapper.eq("userid", attendapprove.getWorkid());
	            queryWrapper.eq("attenddate", str);
	            Attendance attendance = attendanceService.getOne(queryWrapper);
	            if (attendance!=null)  {
	            	attendance.setAttendtype(Integer.parseInt(attendapprove.getType()));
	            	attendance.setAttenddate(DateUtils.strToDate(str));
	            	attendanceService.updateById(attendance);
	            } else {
	            	attendance = new Attendance();
	            	attendance.setId(CommonUtils.getID());
	            	attendance.setUserid(attendapprove.getWorkid());
	            	attendance.setAttenddate(DateUtils.strToDate(str));
	            	attendance.setCreatetime(DateUtils.getCurrentDate());
	            	attendance.setAttendtype(0);
	            	attendanceService.save(attendance);
	            }
    		}
    	}        
        Appointment app = new Appointment();
        app.setAppointId(attendapprove.getWorkid());
        app.setAppointTime(DateUtils.dateToStr(attendapprove.getCreatetime()));
        appointmentMapper.updateHoliday(app);
        Messages m = new Messages();
        m.setId(CommonUtils.getID());
        m.setMsgType(2);
        m.setNormalMsgType(6);
        m.setCurrentUserId(attendapprove.getWorkid());
        m.setDelFlag(0);

        m.setRemark("您的请假申请已通过"+"\n"+"开始日期:"+startTime+"\n"+"结束日期:"+endTime);
        m.setMsgTime(DateUtils.getCurrentTimeDateStr());
        messagesService.save(m);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "考勤审批-驳回")
    @ApiOperation(value = "考勤审批-驳回", notes = "考勤审批-驳回")
    @RequestMapping(value = "/unpass", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> unpass(@RequestParam(name = "id") String id,
                                 @RequestParam(name = "remark",required = false) String remark,
                                 HttpServletRequest request) {
        Attendapprove attendapprove = attendapproveService.getById(id);
        attendapprove.setApprove("2");
        attendapprove.setRemark(remark);
        attendapprove.setApprovetime(DateUtils.getCurrentDate());
        attendapprove.setApproveman(UserUtil.getUserId(request, sysBaseAPI));
        attendapproveService.updateById(attendapprove);
        Messages m = new Messages();
        m.setId(CommonUtils.getID());
        m.setMsgType(2);
        m.setNormalMsgType(6);
        m.setCurrentUserId(attendapprove.getWorkid());
        m.setDelFlag(0);
        String starTime = DateUtils.dateToStr(attendapprove.getStartTime());
        String stopTome = DateUtils.dateToStr(attendapprove.getStopTime());
        m.setMsgTime(DateUtils.getCurrentTimeDateStr());
        m.setRemark("您的请假被驳回，请重新申请"+"\n"+
                "请假开始时间:"+starTime+"\n"+
                "请假结束时间:"+stopTome +"\n"+
                "驳回原因:"+remark);
        messagesService.save(m);
        return Result.OK("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param attendapprove
     * @return
     */
    @AutoLog(value = "考勤审批-编辑")
    @ApiOperation(value = "考勤审批-编辑", notes = "考勤审批-编辑")
    //@RequiresPermissions("org.jeecg.modules:attendapprove:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody Attendapprove attendapprove) {
        attendapproveService.updateById(attendapprove);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "考勤审批-通过id删除")
    @ApiOperation(value = "考勤审批-通过id删除", notes = "考勤审批-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:attendapprove:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        attendapproveService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "考勤审批-批量删除")
    @ApiOperation(value = "考勤审批-批量删除", notes = "考勤审批-批量删除")
    //@RequiresPermissions("org.jeecg.modules:attendapprove:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.attendapproveService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "考勤审批-通过id查询")
    @ApiOperation(value = "考勤审批-通过id查询", notes = "考勤审批-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Attendapprove> queryById(@RequestParam(name = "id", required = true) String id) {
        Attendapprove attendapprove = attendapproveService.getById(id);
        if (attendapprove == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(attendapprove);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param attendapprove
     */
    //@RequiresPermissions("org.jeecg.modules:attendapprove:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Attendapprove attendapprove) {
        return super.exportXls(request, attendapprove, Attendapprove.class, "考勤审批");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("attendapprove:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Attendapprove.class);
    }

}
